<template>
    <el-card>
        <el-form :inline="true" class="form">
            <el-form-item label="职位搜索">
                <el-input placeholder="请输入搜索职位关键字" v-model="keyword"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :disabled="keyword?false:true" @click="search">搜索</el-button>
                <el-button type="primary" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card style="margin: 10px 0;">
        <el-button type="primary" icon="Plus" @click="addRole">添加职位</el-button>
        <el-table border style="margin: 10px 0;" :data="allRole">
            <el-table-column type="index" align="center" label="#"></el-table-column>
            <el-table-column label="ID" align="center" prop="id"></el-table-column>
            <el-table-column label="职位名称" align="center" show-overflow-tooltip prop="roleName"></el-table-column>
            <el-table-column label="创建时间" align="center" show-overflow-tooltip prop="createTime"></el-table-column>
            <el-table-column label="更新时间" align="center" show-overflow-tooltip prop="updateTime"></el-table-column>
            <el-table-column label="操作" width="280px" align="center">
                <template #="{row,$index}">
                    <el-button type="primary" icon="User" size="small" @click="setPermisstion(row)">分配权限</el-button>
                    <el-button type="primary" icon="Edit" size="small" @click="updateRole(row)">编辑</el-button>
                    <el-popconfirm title="确定删除?" width="260px" @confirm="removeRole(row.id)">
                        <template #reference>
                            <el-button type="primary" icon="Delete" size="small" >删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :background="true"
        layout=" prev, pager, next, jumper, ->,sizes,total,"
        :total="total"
        @current-change="getHasRole"
        @size-change="sizeChange"
        />
    </el-card>
    <!-- 添加与更新职位的对话框 -->
    <el-dialog v-model="dialogVisite" :title="RoleParams.id?'更新职位':'添加职位'">
        <el-form :model="RoleParams" :rules="rules" ref="form">
            <el-form-item label="职位名称" prop="roleName">
                <el-input placeholder="请输入职位名称" v-model="RoleParams.roleName"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="dialogVisite=false">取消</el-button>
            <el-button type="primary" @click="save">确定</el-button>
        </template>
    </el-dialog>
    <!-- 抽屉组件：分配职位的菜单与按钮权限 -->
    <el-drawer v-model="drawer">
        <template #header>
        <h4>分配权限</h4>
        </template>
        <template #default>
            <el-tree ref="tree"
                style="max-width: 600px"
                :data="menuArr"
                show-checkbox
                node-key="id"
                default-expand-all
                :default-checked-keys="selectArr"
                :props="defaultProps"
            />
        </template>
        <template #footer>
        <div style="flex: auto">
            <el-button @click="drawer=false">取消</el-button>
            <el-button type="primary" @click="handler">确定</el-button>
        </div>
        </template>
    </el-drawer>
</template>
<script setup lang="ts">
import { reqAddOrUpdateRole, reqAllMenuList, reqAllRoleList, reqRemoveRole, reqSetPermisstion } from '@/api/acl/role';
import { MenuList, MenuResponseData, Records, RoleResponseData } from '@/api/acl/role/type';
import { nextTick, onMounted, reactive, ref } from 'vue';
import useLayOutSettingStore from '@/store/modules/setting';
import { RoleData } from '@/api/acl/role/type';
import { ElMessage } from 'element-plus';
//获取树组件实例
let tree=ref<any>();
//准备数组用于存储勾选节点的ID
let selectArr=ref<number[]>([]);
//定义数组存储权限数据
let menuArr=ref<MenuList>([]);
//控制抽屉显示与隐藏
let drawer=ref<boolean>(false)
//获取form组件实例
let form=ref<any>();
//收集新增岗位的数据
let RoleParams=reactive<RoleData>({
    roleName: ''
})
let settingStore=useLayOutSettingStore();
//控制对话框的显示与隐藏
let dialogVisite=ref<boolean>(false);

let pageNo=ref<number>(1);
let pageSize=ref<number>(10);

let keyword=ref<string>('');

//存储全部已有的职位
let allRole=ref<Records>([]);
//总个数
let total=ref<number>(0);
const defaultProps={
    children: 'children',
    label: 'name',
}

onMounted(()=>{
    //获取职位的请求
    getHasRole();
})
const getHasRole=async (pager=1)=>{
    //修改当前的页码
    let result:RoleResponseData=await reqAllRoleList(pageNo.value,pageSize.value,keyword.value);
    console.log('获取职位');
    console.log(result);
    if(result.code==200){
        total.value=result.data.total;
        allRole.value=result.data.records;
    }
}
const sizeChange=()=>{
    getHasRole();
}
//搜索按钮
const search=()=>{
    getHasRole();
    keyword.value='';
}

const reset=()=>{
    settingStore.refsh=!settingStore.refsh;
}

//添加职位
const addRole=()=>{
    //对话框显示
    dialogVisite.value=true;
    //数据清空
    Object.assign(RoleParams,{
        roleName: '',
        id:'',
    })
    //清空上一次表单校验的结果
    nextTick(()=>{
        form.value.clearValidate();
    })
}
//更新已有的职位按钮
const updateRole=(row:RoleData)=>{
    dialogVisite.value=true;
    Object.assign(RoleParams,row);
    nextTick(()=>{
        form.value.clearValidate();
    })
}


const validatorRoleName=(rule: any, value: any, callback: any)=>{
    if(value.trim().length>=2){
        callback();
    }
    else{
        callback(new Error("职位名称至少两位"));
    }
}
//确定按钮
const save=async ()=>{
    //表单校验的结果
    await form.value.validate();
    //添加或更新职位
    let result=await reqAddOrUpdateRole(RoleParams);
    console.log("添加或更新职位");
    console.log(result);
    if(result.code==200){
        ElMessage({
            type: "success",
            message: RoleParams.id?'更新成功':'添加成功',
        })
        //获取已有的职位
        getHasRole(RoleParams.id?pageNo.value:1);
    }
    else{
        ElMessage({
            type: "error",
            message: RoleParams.id?'更新失败':'添加失败',
        })
    }
    dialogVisite.value=false
}



//职位校验规则
const rules={
    roleName: [{required: true,trigger: 'blur',validator:validatorRoleName}],
}
//分配权限按钮的回调
const setPermisstion=async (row:RoleData)=>{
    drawer.value=true;
    //收集当前要分类权限的职位的数据
    Object.assign(RoleParams,row);
    let result:MenuResponseData=await reqAllMenuList(RoleParams.id as number);
    console.log('权限数据');
    console.log(result);
    if(result.code==200){
        menuArr.value=result.data;
        selectArr.value= fillterSelectAll(menuArr.value,[]);
        console.log(selectArr.value);
    }
}

const fillterSelectAll=(allData:any,initArr:any)=>{
    allData.forEach((item:any)=>{
        if(item.children&&item.children.length>0){
            fillterSelectAll(item.children,initArr);
        }
        else if(item.select&&item.level==4){
            initArr.push(item.id);
        }
    })
    return initArr;
}

//抽屉确定按钮
const handler=async ()=>{
    //职位的ID
    const roleId=RoleParams.id;
    //选择节点的ID
    let arr=tree.value.getCheckedKeys();
    //半选ID
    let arr1=tree.value.getHalfCheckedKeys();
    let permissionId=arr.concat(arr1);
    //下发相应的权限
    let result=await reqSetPermisstion(roleId as number,permissionId)
    console.log('下发权限');
    console.log(result);
    if(result.code==200){
        ElMessage.success("分配权限成功");
        window.location.reload();
    }
    drawer.value=false
}
//删除已有的职位
const removeRole=async (id:number)=>{
    let result=await reqRemoveRole(id);
    if(result.code==200){
        ElMessage.success("删除成功");
        getHasRole(allRole.value.length>1?pageNo.value:pageNo.value-1);
    }
    else{
        ElMessage.error("删除失败");
    }
}
</script>
<style scoped>
.form{
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
}
</style>